<template>
  <div class="image-swiper-container" :style="{ height: height }" v-if="imageItems && imageItems.length > 0">
    <Swiper :modules="swiperModules" :navigation="navigation" :pagination="pagination"
            :autoplay="autoplay ? { delay: autoplayDelay } : false" :loop="imageItems.length > 1" class="image-swiper">
      <SwiperSlide v-for="item in imageItems" :key="item.id">
        <div class="image-slide-content">
          <img :src="getImageUrl(item)" :alt="item.title" class="slide-image" @load="onImageLoad"
               @error="onImageError" />

          <div class="image-title-overlay" v-if="showTitle">
            <h3 class="image-title">{{ item.title }}</h3>
          </div>
          <!-- 加载状态 -->
          <div class="image-loading" v-if="!item.loaded">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>
          <!-- 错误状态 -->
          <div class="image-error" v-if="item.error">
            <div class="error-icon">📷</div>
            <p>图片加载失败</p>
          </div>
        </div>
      </SwiperSlide>
    </Swiper>
  </div>
  <!-- 空状态 -->
  <div class="image-swiper-empty" :style="{ height: height }" v-else>
    <div class="empty-icon">📷</div>
    <p>暂无图片信息</p>
  </div>

</template>

<script lang="ts">
import { defineComponent, PropType, reactive } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import SwiperCore, { Navigation, Pagination, Autoplay } from 'swiper';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

//导入全局设置和API
import {useGlobSetting} from "/@/hooks/setting";
import {getImageFileApi} from "/@/api/platform/file";

// 安装 Swiper 模块
SwiperCore.use([Navigation, Pagination, Autoplay]);

// 定义图片项数据类型
interface ImageItem {
  id: string | number;
  title: string;
  url: string;
  content?: string; // JSON字符串，包含url等信息
  loaded?: boolean;
  error?: boolean;
}

export default defineComponent({
  name: 'ImageSwiper',
  components: {
    Swiper,
    SwiperSlide,
  },
  props: {
    // 图片数据数组
    imageItems: {
      type: Array as PropType<ImageItem[]>,
      required: true,
      default: () => [],
    },
    // 图片URL前缀
    imageUrlPrefix: {
      type: String,
      default: '',
    },
    // 轮播高度
    height: {
      type: String,
      default: '100%',
    },
    // 是否自动播放
    autoplay: {
      type: Boolean,
      default: true,
    },
    // 自动播放延迟时间
    autoplayDelay: {
      type: Number,
      default: 10000,
    },
    // 是否显示导航按钮
    navigation: {
      type: Boolean,
      default: true,
    },
    // 分页器配置
    pagination: {
      type: [Object, Boolean],
      default: () => ({ type: 'bullets', clickable: true }),
    },
    // 是否显示标题
    showTitle: {
      type: Boolean,
      default: true,
    },
    // 图片适配方式
    objectFit: {
      type: String as PropType<'cover' | 'contain' | 'fill' | 'scale-down'>,
      default: 'cover',
    },
  },
  setup(props) {
    //获取全局配置
    const {uploadUrl}= useGlobSetting()

    // 构建完整的图片URL前缀
    const imageUrlPrefix=uploadUrl  + getImageFileApi;

    // 处理图片加载成功
    const onImageLoad = (event: Event) => {
      const img = event.target as HTMLImageElement;
      const slideElement = img.closest('.image-slide-content');
      if (slideElement) {
        slideElement.classList.add('loaded');
      }
    };

    // 处理图片加载失败
    const onImageError = (event: Event) => {
      const img = event.target as HTMLImageElement;
      const slideElement = img.closest('.image-slide-content');
      if (slideElement) {
        slideElement.classList.add('error');
      }
    };


    const getImageUrl = (item: ImageItem):string => {
      try {
        // 如果直接有 url 属性（drawer 传入的格式）
        if (item.url) {
          return imageUrlPrefix + item.url;
        }

        // 如果有 content 属性（Index.vue 传入的格式）
        if (item.content) {
          const parsedContent = JSON.parse(item.content);
          if (parsedContent.url){
            return imageUrlPrefix + parsedContent.url;
          }
        }

        return '';
      } catch (error) {
        console.error('解析图片URL失败:', item, error);
        return '';
      }
    };

    // 返回 Swiper 模块
    const swiperModules = [Navigation, Pagination, Autoplay];
    return {
      onImageLoad,
      onImageError,
      swiperModules,
      getImageUrl
    };
  },
});
</script>

<style scoped lang="less">
// 优化后的 ImageSwiper 样式结构
.image-swiper-container {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  // 第三方 Swiper 组件样式
  .image-swiper {
    width: 100%;
    height: 100%;

    // 我们的幻灯片内容样式
    .image-slide-content {
      width: 100%;
      height: 100%;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;

      .slide-image {
        width: 100%;
        height: 100%;
        object-fit: v-bind(objectFit);
        transition: opacity 0.3s ease;
        opacity: 0;
      }

      // 加载完成状态
      &.loaded {
        .slide-image {
          opacity: 1;
        }

        .image-loading {
          display: none;
        }
      }

      // 错误状态
      &.error {
        .slide-image {
          display: none;
        }

        .image-loading {
          display: none;
        }
      }

      // 标题遮罩层
      .image-title-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.50);
        padding: 5px 0;
        //backdrop-filter: blur(5px);

        z-index: 99;

        .image-title {
          text-align: center;
          color: white;
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7);
          line-height: 1.4;
        }
      }

      // 加载和错误状态的通用样式
      .image-loading,
      .image-error {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;

        p {
          margin: 0;
          font-size: 14px;
        }
      }

      // 加载状态特有样式
      .image-loading {
        .loading-spinner {
          width: 40px;
          height: 40px;
          border: 3px solid #f3f3f3;
          border-top: 3px solid #007bff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin: 0 auto 10px;
        }
      }

      // 错误状态特有样式
      .image-error {
        .error-icon {
          font-size: 48px;
          margin-bottom: 10px;
          opacity: 0.5;
        }
      }
    }
  }
}

// 空状态样式（独立的，不在嵌套内）
.image-swiper-empty {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;

  .empty-icon {
    font-size: 3rem;
    margin-bottom: 5%;
    opacity: 0.5;
  }

  p {
    margin: 0;
    font-size: 1rem;
  }
}

// 加载动画
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 第三方组件样式 - 必须使用 :deep() 穿透
:deep(.swiper-button-next),
:deep(.swiper-button-prev) {
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  width: 30px;
  height: 30px;
  border-radius: 50%;

  &:after {
    font-size: 16px;
  }

  &:hover {
    color: white;
    background: rgba(0, 0, 0, 0.5);
    transform: scale(1.1);
  }
}

:deep(.swiper-pagination-bullets) {
  top: -6px !important;
  bottom: auto !important;
  text-align: center;

  .swiper-pagination-bullet {
    width: 20px !important;
    height: 3px !important;
    border-radius: 2px !important;
    background: rgba(255, 255, 255, 0.4) !important;
    margin: 0 7px !important;

    &.swiper-pagination-bullet-active {
      background: rgba(255, 255, 255, 0.9) !important;
      transform: scaleX(1.5) !important;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .image-swiper-container {
    .image-swiper {
      .image-slide-content {
        .image-title-overlay {
          padding: 20px 15px 10px;

          .image-title {
            font-size: 14px;
          }
        }
      }
    }
  }

  :deep(.swiper-button-next),
  :deep(.swiper-button-prev) {
    width: 35px;
    height: 35px;

    &:after {
      font-size: 14px;
    }
  }
}
</style>
